package sugges;

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import run.MainScreen;

public class Suggestion extends JFrame {
	private static File f;

	// ********************GUI*******************//
	private String fileSuggest[] = { "ICT", "Lịch sử", "Địa lí", "Khoa học",
			"Giải trí", "Khác" };
	private Box vertBox;
	private JComboBox listFile = new JComboBox(fileSuggest);
	private Box viewBox;
	private Box inputBox;
	private Box buttonBox;
	private JList jList1 = new JList();
	private JScrollPane jScrollPane1 = new JScrollPane();
	private JTextPane inputTextPanel = new JTextPane();
	private JButton btnAddWord = new JButton();
	private JButton btnDeleteWord = new JButton();

	// ********************GUI*******************//

	public Suggestion() {
		try {
			jbInit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void displayList() {
		String str = (String) listFile.getSelectedItem();
		ArrayList al = printList(str);
		jList1.setListData(al.toArray());
		// move scroll bar to top
		jList1.setSelectedIndex(0);
		jScrollPane1.getVerticalScrollBar().setValue(0);
	}

	private void jbInit() {
		this.show();
		this.setBounds(0, 0, 250, 720);
		this.setBackground(new Color(174, 190, 212));
		this.setTitle("Suggestion");
		vertBox = Box.createVerticalBox();
		viewBox = Box.createHorizontalBox();
		inputBox = Box.createHorizontalBox();
		buttonBox = Box.createHorizontalBox();
		listFile.setMaximumSize(new Dimension(200, 60));

		// Init list on first time view
		displayList();

		listFile.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				displayList();
			}
		});
		inputBox.setPreferredSize(new Dimension(20, 80));
		inputTextPanel
				.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
		// list
		jList1.setMaximumSize(new Dimension(332, 50000));
		jList1.setMinimumSize(new Dimension(332, 100));
		jList1.setPreferredSize(new Dimension(332, 5000));
		jList1.setToolTipText("Suggestion Words");
		jList1.setActionMap(null);
		jScrollPane1.setAutoscrolls(true);
		jScrollPane1.setMaximumSize(new Dimension(2147483647, 2147483647));
		jScrollPane1.setPreferredSize(new Dimension(250, 550));
		// add
		btnAddWord.setMaximumSize(new Dimension(100, 37));
		btnAddWord.setPreferredSize(new Dimension(100, 37));
		ImageIcon add = new ImageIcon(this.getClass().getResource(
				"/img/add.png"));
		btnAddWord.setIcon(add);
		btnAddWord.setToolTipText("Thêm từ mới");
		btnAddWord.addActionListener(new CListener());

		// delete
		btnDeleteWord.setMaximumSize(new Dimension(100, 37));
		btnDeleteWord.setPreferredSize(new Dimension(100, 37));
		ImageIcon del = new ImageIcon(this.getClass().getResource(
				"/img/del.png"));
		btnDeleteWord.setIcon(del);
		btnDeleteWord.setToolTipText("Xóa từ");
		btnDeleteWord.addActionListener(new CListener());
		// BUILD GUI
		viewBox.add(Box.createHorizontalStrut(10));
		viewBox.add(jScrollPane1);
		viewBox.add(Box.createHorizontalStrut(10));
		jScrollPane1.getViewport().add(jList1);

		vertBox.add(Box.createVerticalStrut(10));
		vertBox.add(viewBox);
		vertBox.add(Box.createVerticalStrut(10));
		vertBox.add(listFile);
		vertBox.add(Box.createVerticalStrut(10));
		vertBox.add(inputBox);
		inputBox.add(Box.createHorizontalStrut(10));
		inputBox.add(inputTextPanel);
		inputBox.add(Box.createHorizontalStrut(10));
		vertBox.add(Box.createVerticalStrut(10));
		vertBox.add(buttonBox);
		buttonBox.add(btnAddWord);
		buttonBox.add(Box.createHorizontalStrut(20));
		buttonBox.add(btnDeleteWord);
		add(vertBox, BorderLayout.CENTER);
	}

	public static ArrayList getMatches(String s) {
		switch (MainScreen.cc.getTheme()) {
		case 1:
			f = new File("sugges/english.txt");
			break;
		case 2:
			f = new File("sugges/ict.txt");
			break;
		case 3:
			f = new File("sugges/history.txt");
			break;
		case 4:
			f = new File("sugges/geography.txt");
			break;
		case 5:
			f = new File("sugges/science.txt");
			break;
		case 6:
			f = new File("sugges/entertainment.txt");
			break;
		case 7:
			f = new File("sugges/khac.txt");
			break;
		default:
			JOptionPane.showMessageDialog(null,
					" Không tìm thấy file Suggestion \n", "File not found",
					JOptionPane.OK_OPTION);
			break;
		}

		s = s.toLowerCase();

		// build the pattern to match
		StringBuffer sb = new StringBuffer(100);
		sb.append("^");
		ArrayList wordList = new ArrayList();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '*' || s.charAt(i) == ' ') {
				sb.append(".");
			} else {
				sb.append(s.charAt(i));
			}
		}
		sb.append("$");

		// read from the word file
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(f);
			br = new BufferedReader(fr);

			boolean b = true;

			// read through all lines
			while (b) {
				String word = br.readLine();
				if (word == null)
					b = false; // end has been reached
				else {
					// try and find a match to the specified pattern
					Pattern p = Pattern.compile(sb.toString());
					Matcher m = p.matcher(word);
					boolean result = m.find();
					if (result) {
						wordList.add(word); // word was a match
					}
				}
			}
		} catch (FileNotFoundException ex) {
			System.out.println(ex.toString());
			JOptionPane.showMessageDialog(null,
					" Không tìm thấy file Suggestion \n", "File not found",
					JOptionPane.OK_OPTION);
		} catch (IOException ex) {
			System.out.println(ex.toString());
		}
		return wordList;
	}

	public static ArrayList printList(String s) {

		if (s.equals("ICT"))
			f = new File("sugges/ict.txt");
		else if (s.equals("Lịch sử"))
			f = new File("sugges/history.txt");
		else if (s.equals("Địa lí"))
			f = new File("sugges/geography.txt");
		else if (s.equals("Khoa học"))
			f = new File("sugges/science.txt");
		else if (s.equals("Giải trí"))
			f = new File("sugges/entertainment.txt");
		else if (s.equals("Khác"))
			f = new File("sugges/khac.txt");

		ArrayList wordList = new ArrayList();
		// read from the word file
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(f);
			br = new BufferedReader(fr);

			boolean b = true;

			// read through all lines
			while (b) {

				String word = br.readLine();
				if (word == null)
					b = false; // end has been reached
				else
					wordList.add(word);
			}
		} catch (FileNotFoundException ex) {
			System.out.println(ex.toString());
			JOptionPane.showMessageDialog(null,
					" Không tìm thấy file Suggestion \n", "File not found",
					JOptionPane.OK_OPTION);
		} catch (IOException ex) {
			System.out.println(ex.toString());
		}
		return wordList;
	}

	private int binarySearch(ArrayList al, String str) {
		int begin = 0;
		int end = al.size() - 1;
		int found = 0;
		while (begin <= end) {
			found = (begin + end) / 2;
			String word = (String) al.get(found);
			if (str.equals(word))
				return -1;
			else if (str.compareTo(word) < 0)
				end = found - 1;
			else
				begin = found + 1;
		}
		return found;
	}

	class CListener implements ActionListener {
		private String removeSpace(String inputText) {
			inputText = inputText.trim();
			String[] splitWord = inputText.split(" ");
			inputText = "";
			for (int i = 0; i < splitWord.length; i++) {
				inputText = inputText.concat(splitWord[i]);
			}
			inputText += "\n";
			return inputText;

		}

		public void actionPerformed(ActionEvent e) {
			String fileName = (String) listFile.getSelectedItem();

			if (fileName.equals("ICT"))
				fileName = "sugges/ict.txt";
			else if (fileName.equals("Lịch sử"))
				fileName = "sugges/history.txt";
			else if (fileName.equals("Địa lí"))
				fileName = "sugges/geography.txt";
			else if (fileName.equals("Khoa học"))
				fileName = "sugges/science.txt";
			else if (fileName.equals("Giải trí"))
				fileName = "sugges/entertainment.txt";
			else if (fileName.equals("Khác"))
				fileName = "sugges/khac.txt";

			if (e.getSource().equals(btnAddWord)) {
				// Chèn từ & sắp xếp theo thứ tự từ điển
				String inputText = inputTextPanel.getText() + '\n';
				if (inputText.equals("\n")) {
					JOptionPane.showMessageDialog(null, "Bạn chưa nhập từ mới");
				} else {
					String[] textSplit = inputText.split("\n");
					for (String subInputText : textSplit) {
						subInputText = removeSpace(subInputText);
						try {
							String fileContent = TextFile.read(fileName);
							String[] str = fileContent.split("\n");
							ArrayList<String> al = new ArrayList<String>();
							for (String s : str) {
								al.add(s + '\n');
							}

							int indexToAdd = binarySearch(al, subInputText
									.toLowerCase());
							if (indexToAdd == -1)
								JOptionPane.showMessageDialog(null,
										"Đã có từ : " + subInputText);
							else {
								al.add(indexToAdd, subInputText.toLowerCase());
								Collections.sort(al);
								fileContent = "";
								for (String s : al)
									fileContent += s;
								TextFile.write("buffer.txt", fileContent);
								TextFile text = new TextFile("buffer.txt");
								text.write(fileName);
								displayList();
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				}

			} else if (e.getSource().equals(btnDeleteWord)) {
				int response = JOptionPane.showConfirmDialog(null,
						"Bạn chắc chắn muốn xóa chứ ?", "Confirm Delete",
						JOptionPane.YES_NO_OPTION);
				if (response == JOptionPane.YES_OPTION) {
					String removeStr = (String) jList1.getSelectedValue() + '\n';
					try {
						String fileContent = TextFile.read(fileName);
						String[] str = fileContent.split("\n");
						ArrayList<String> al = new ArrayList<String>();
						for (String s : str) {
							al.add(s + '\n');
						}

						al.remove(removeStr);
						// System.out.print(al.toString());
						fileContent = "";
						for (String s : al)
							fileContent += s;
						TextFile.write("buffer.txt", fileContent);
						TextFile text = new TextFile("buffer.txt");
						text.write(fileName);
						displayList();

					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}
	}
}
